package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import csc.daonjpa.java.domain.Card;

@Repository
public class CardDAO {
	@PersistenceContext
	private EntityManager em;

	/**
	 * @return all cards from Card table
	 */
	@Transactional
	public List<Card> getCards() {
		// EntityManager em = TransactionManager.getEntityManager();
		TypedQuery<Card> query = em.createQuery("SELECT a FROM Card a",
				Card.class);
		List<Card> cards = null;
		cards = query.getResultList();
		return cards;
	}

	/**
	 * Add card to card table
	 * 
	 * @param card
	 *            Card entity that contains mapped with each column in Card
	 *            table
	 * @return
	 */
	@Transactional
	public boolean addCard(Card card) {
		// EntityManager em = TransactionManager.getEntityManager();
		em.persist(card);
		return true;
	}

	/**
	 * Get all cards belong to the customer with loginid = custLoginId
	 * 
	 * @param custLoginId
	 *            Customer's loginid
	 * @return
	 */
	@Transactional
	public List<Card> getCardsByCustomerId(String custLoginId) {
		// EntityManager em = TransactionManager.getEntityManager();
		TypedQuery<Card> query = null;
		try {
			query = em.createQuery("SELECT a FROM Card a WHERE custId = ?",
					Card.class).setParameter(1, custLoginId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<Card> cards = query.getResultList();
		if (!cards.isEmpty()) {
			return cards;
		}
		return null;
	}

	@Transactional
	public Card getCardByTypeAndName(String cardBank, String cardType) {
		TypedQuery<Card> query = null;
		try {
			query = em
					.createQuery(
							"SELECT a FROM Card a WHERE cardType = :type AND bank = :bank ",
							Card.class);
			query.setParameter("type", cardType);
			query.setParameter("bank", cardBank);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Remember to check null
		List<Card> cards = query.getResultList();
		if (!cards.isEmpty()) {
			return cards.get(0);
		}
		return null;
	}
}
